<template>
  <div>
    <el-dialog :close-on-click-modal="false" title="接单区域" :modal-append-to-body="false" :visible.sync="areaShow" :before-close="closeDialog" class="tl size_13" width="1200px">
      <el-form :model="areaInfo" ref="form" label-width="150px">
        <el-form-item label="标题：">
          <el-col :span="12">
            <el-input type="text" :rows="6" clearable placeholder="请输入标题" v-model="areaInfo.title" autocomplete="off"> </el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="extract_area_tip" style="margin-bottom: 10px">Tip:双击白色圆点可清除该圆点</div>
      <div id="containerMap"></div>
      <div class="extract_area_bottom">
        <el-button :loading="$store.state.isLoading" type="primary" size="medium" @click="saveArea"> 保存 </el-button>
        <!-- <el-button :loading="$store.state.isLoading" type="danger" size="medium" @click="clearArea"> 清空 </el-button> -->
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="添加" class="tl size_13" width="800px" :visible.sync="jwdShow">
      <el-form :model="areaInfo" ref="form" label-width="150px">
        <el-form-item label="中心点地区经纬度">
          <el-col :span="12">
            <el-input placeholder v-model="JWD" clearable>
              <template slot="append">
                <a target="_blank" :href="'https://lbs.qq.com/tool/getpoint/index.html'">
                  <el-button :loading="$store.state.isLoading" size="mini">查看经纬度</el-button>
                </a>
              </template>
            </el-input>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button :loading="$store.state.isLoading" type="primary" @click="nextbtn()">下一步</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
const GPSKEY = "9ea145d7d33cad98b37ddb1eb43dcb2d";
export default {
  name: "extract_area",
  data() {
    return {
      jwdShow: false,
      JWD: "",
      areaInfo: {},
      areaShow: false,
      polyEditor: null,
      polygon: null,
      map: null,
    };
  },
  components: {},
  created() {},
  methods: {
    nextbtn() {
      if (!this.JWD) {
        this.$message.error("请输入经纬度");
        return;
      }
      var JWD = this.JWD;
      var jwd_ar = JWD.split(",");
      this.areaInfo.longitude = jwd_ar[1]; //经度
      this.areaInfo.latitude = jwd_ar[0]; //纬度
      this.jwdShow = false;

      this.init(this.areaInfo);
    },
    clearArea() {
      let params = {};
      params.id = this.areaInfo.id;
      params.map = "";
      this.$api.getRider.setStoreDeliveryArea(params).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("编辑成功");
          this.areaShow = false;
        } else {
          this.$fnc.alertError(res.data.result);
        }
      });
    },
    getCenter(pointArray) {
      let sortedLongitudeArray = pointArray.map((item) => item.longitude).sort();
      let sortedLatitudeArray = pointArray.map((item) => item.latitude).sort();
      let centerLongitude = ((parseFloat(sortedLongitudeArray[0]) + parseFloat(sortedLongitudeArray[sortedLongitudeArray.length - 1])) / 2).toFixed(4);
      let centerLatitude = ((parseFloat(sortedLatitudeArray[0]) + parseFloat(sortedLatitudeArray[sortedLatitudeArray.length - 1])) / 2).toFixed(4);
      let centerPoint = {
        longitude: centerLongitude,
        latitude: centerLatitude,
      };
      return centerPoint;
    },
    saveArea() {
      let arr = this.polygon.getPath();
      let n_arr = [];
      let n_arr2 = [];
      arr.forEach((item, i) => {
        n_arr.push([item.lng, item.lat]);
        n_arr2.push({ longitude: item.lng, latitude: item.lat });
      });
      let params = {};
      params.map = JSON.stringify(n_arr);
      params.title = this.areaInfo.title;
      let center = this.getCenter(n_arr2);
      params.latitude = center.latitude;
      params.longitude = center.longitude;
      let apiName = "";
      if (this.areaInfo.id) {
        params.id = this.areaInfo.id;
        apiName = "edit_receiving_area";
      } else {
        apiName = "add_receiving_area";
      }
      this.$api.getReceiving[apiName](params).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("编辑成功");
          this.areaShow = false;
          this.$emit("refresh");
        } else {
          this.$message.error(res.data.result);
        }
      });
    },
    get_detail(item) {
      if (item && item.id) {
        this.$api.getReceiving.single_receiving_area({ id: item.id }).then((res) => {
          if (res.data.code == 200) {
            this.areaInfo = res.data.result;
            this.init(this.areaInfo);
          }
        });
      } else {
        this.areaInfo = {
          longitude: "",
          latitude: "",
        };
        this.jwdShow = true;
      }
    },
    init(item) {
      this.areaShow = true;
      this.$nextTick(() => {
        var url = `https://webapi.amap.com/maps?v=2.0&key=${GPSKEY}&callback=onLoad&plugin=AMap.PolygonEditor`;
        var jsapi = document.createElement("script");
        jsapi.charset = "utf-8";
        jsapi.src = url;
        document.head.appendChild(jsapi);

        window.onLoad = () => {
          var that = this;
          that.map = new AMap.Map("containerMap", {
            resizeEnable: true,
            mapStyle: "amap://styles/light",
            zoom: 12,
          });

          that.map.plugin(["AMap.ControlBar", "AMap.MapType", "AMap.Scale"], function () {
            var controlBar = new AMap.ControlBar({
              showZoomBar: true,
              showControlButton: true,
              position: { bottom: "0px", right: "10px" },
            });
            //地图类型切换
            var type = new AMap.MapType({
              defaultType: 0, //使用2D地图
            });
            var scale = new AMap.Scale();
            that.map.addControl(controlBar);
            that.map.addControl(scale);
            that.map.addControl(type);

            let areaList = [];
            if (that.areaInfo.map && that.areaInfo.map != "[]") {
              areaList = JSON.parse(that.areaInfo.map);
            } else {
              that.$message.success("已初始化点位，请规划区域");
              areaList.push([that.areaInfo.longitude, that.areaInfo.latitude]);
              areaList.push([that.areaInfo.longitude - 0.005, that.areaInfo.latitude - 0.005]);
              areaList.push([that.areaInfo.longitude - 0.005, that.areaInfo.latitude - 0.001]);
            }
            console.log(areaList);
            that.polygon = new AMap.Polygon({
              path: areaList,
              strokeColor: "#FF33FF",
              strokeWeight: 6,
              strokeOpacity: 0.2,
              fillOpacity: 0.4,
              fillColor: "#1791fc",
              zIndex: 50,
              bubble: true,
            });
            that.map.add([that.polygon]);
            that.map.setFitView();
            that.polyEditor = new AMap.PolygonEditor(that.map, that.polygon);
            that.polyEditor.open();
          });
        };
      });
    },
    closeDialog() {
      this.areaShow = false;
      this.polyEditor = null;
      this.polygon = null;
      this.map = null;
      this.areaInfo = {};
    },
  },
};
</script>
<style lang="less" scoped>
#containerMap {
  width: 100%;
  height: 60vh;
}

.extract_area_tip {
  width: 100%;
  text-align: center;
  font-size: 14px;
  color: red;
}
.extract_area_bottom {
  width: 100%;
  margin-top: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
